package com.example.news.Video;

import android.content.Context;
import android.media.MediaPlayer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.news.R;

import java.util.List;

public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.ViewHolder> {
    Context context;
    List<Girl> list;
    public VideoAdapter(Context context, List<Girl> list) {
        this.context= context;
        this.list = list;
    }


    @NonNull
    @Override
    public VideoAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_girl,parent,false);
        return new VideoAdapter.ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull VideoAdapter.ViewHolder holder, int position) {
        holder.videoView.setVideoPath(list.get(position).getVideoUrl());

        holder.videoView.start();
        holder.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                holder.videoView.start();
                mediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                    @Override
                    public boolean onInfo(MediaPlayer mp, int what, int extra) {
                        return false;
                    }
                });
            }
        });

        holder.videoView.stopPlayback();
        holder.vv_play.setOnClickListener(new View.OnClickListener() {
            boolean isPlay = true;
            @Override
            public void onClick(View v) {
                if(holder.videoView.isPlaying()){
                    holder.vv_play.animate().alpha(1f).start();
                    holder.videoView.pause();
                    isPlay = false;
                }else {
                    holder.vv_play.animate().alpha(0f).start();
                    holder.videoView.start();
                    isPlay= true;
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        if(list != null){
            return list.size();
        }else {
            return 0;
        }
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        VideoView videoView;
        ImageView vv_play;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            videoView = itemView.findViewById(R.id.videoView);
            vv_play = itemView.findViewById(R.id.iv_play);
        }
    }

}
